package piwan.gui;

import piwan.*;
import javax.media.opengl.GL;

import org.fenggui.Display;
import org.fenggui.FengGUI;
import org.fenggui.Label;
import org.fenggui.util.Alignment;
import org.fenggui.util.Point;

public class LabelListOverlay {
	private GL gl = null;
	private Display display = null;
	
	private Label[] labels = null;
	
	private int posLeft = 10, posBottom = 40;
	private Vector2 ovBottomLeft, ovTopRight;
	private int useUpTo;
	private double maxWidth, horizSpacing = 0.005, vertSpacing = 0.005;
	private boolean doReposition;
	
	public LabelListOverlay(MainWindow win, int lblCount, Vector2 pos, double maxWidth) {
		gl = win.getGL();
		display = win.getDisplay();
		labels = new Label[lblCount];
		this.maxWidth = maxWidth;
		ovBottomLeft = pos;
		posLeft = (int)((pos.x+horizSpacing+1.0)/2.0*display.getWidth());
		posBottom = (int)((pos.y+vertSpacing+1.0)/2.0*display.getHeight());
		for(int i=0; i<lblCount; ++i) {
			labels[i] = FengGUI.createWidget(Label.class);
			labels[i].getAppearance().addRenderer("default", labels[i].getAppearance().getRenderer("feedback"));
			labels[i].getAppearance().setAlignment(Alignment.LEFT);
			labels[i].setText(" ");
			labels[i].setMultiline(true);
			labels[i].setWidth((int)(maxWidth/2.0*display.getWidth()));

			display.addWidget(labels[i]);
		}
		useAllLabels();
	}
	
	protected void useAllLabels() {
		useLabelsUpTo(labels.length-1);
	}
	
	protected void useLabelsUpTo(int n) {
		assert(n<labels.length);
		useUpTo = n;
		for(int i=0;i<=useUpTo;++i)
			labels[i].setVisible(true);
		for(int i = useUpTo+1;i<labels.length;++i)
			labels[i].setVisible(false);
		reposition();
	}
	
	public void render() {
		if(doReposition) reposition();
		if(useUpTo!=-1) {
			GameGui.prepareGuiRender(gl, false);
			gl.glColor4d(0.0, 0.0, 0.0, 0.7);
			GameGui.renderRect(gl, ovBottomLeft, ovTopRight);
		}
	}
	
	private void reposition() {
		doReposition=false;
		
		labels[0].setPosition(new Point(posLeft,posBottom) );
		
		for(int i=1; i<labels.length; ++i) {
			labels[i].setPosition(new Point(posLeft,labels[i-1].getY()+labels[i-1].getHeight()));
		}
		if(useUpTo!=-1) {
			double top = ((double)labels[useUpTo].getY() + labels[useUpTo].getHeight())/display.getHeight()*2.0-1.0 + vertSpacing*2.0;
			ovTopRight = new Vector2(ovBottomLeft.x + maxWidth+horizSpacing*2.0, top);
		}
		
	}
	
	protected void setLabel(int i, String st) {
		assert(i<=useUpTo);
		labels[i].setText(st);
		doReposition = true;
		
	}
	
	protected void setMiddle(int i, boolean b) {
		if(b)
			labels[i].getAppearance().setAlignment(Alignment.MIDDLE);
		else
			labels[i].getAppearance().setAlignment(Alignment.LEFT);
	}
	
}
